package cn.cymym.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cymym.comm.CommException;

public class jdbcUtil {
	Logger logger = LoggerFactory.getLogger(jdbcUtil.class);
	private static final String DRIVER;
	private static final String URL;
	private static final String PASSWORD;
	private static final String USER;
	static {
		Properties properties = new Properties();
		InputStream inputStream = jdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
		try {
			
			properties.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
			throw new CommException("加载输入流失败");
		}
		DRIVER = properties.getProperty("driver");
		URL = properties.getProperty("url");
		USER = properties.getProperty("user");
		PASSWORD = properties.getProperty("password");
	}
	/**
	 * 
	 * 加载驱动
	 */
	public static void getDriver() {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new CommException("加载驱动失败");
		}
	}
	/**
	 * 获取连接
	 * @return connection
	 */
	public static Connection getConnection() {
		getDriver();
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(URL, USER, PASSWORD);
			return connection;
		} catch (SQLException e) {
			e.printStackTrace();
			return connection;
		}
	}
	/**
	 * 释放资源
	 * @param resultSet 结果集
	 * @param preparedStatement sql处理
	 * @param connection 连接
	 */
	public static void realse(ResultSet resultSet,PreparedStatement preparedStatement,Connection connection) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			resultSet = null;
			
		}
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			preparedStatement = null;
			
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connection = null;
			
		}
	}
	/**
	 * 释放资源
	 * @param preparedStatement
	 * @param connection
	 */
	public static void realse(PreparedStatement preparedStatement,Connection connection) {
		
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			preparedStatement = null;
			
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connection = null;
			
		}
	}
}
